/* Copyright (c) 2010 EPiServer AB
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
 * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.WebControls;
using EPiServer.Core.PropertySettings;
using EPiServer.Editor.TinyMCE;
using EPiServer.SpecializedProperties;
using EPiServer.Web.PropertyControls;

namespace EPiServer.Municipality.Web.UI.PropertyControls {
    /// <summary>
    /// Summary description for PropertyLongStringExControl.
    /// </summary>
    /// <remarks>
    /// </remarks>
    [PropertySettings(typeof(TinyMCESettings), true)]
    public class PropertyLongStringExControl : PropertyXhtmlStringControl {
        /* *******************************************************************
         *  Methods 
         * *******************************************************************/
        #region public override void CreateDefaultControls()
        /// <summary>
        /// 
        /// </summary>
        public override void CreateDefaultControls() {
            var needContainer = false;
            if (AttributeSourceControl.ControlStyle.IsEmpty == false)
                needContainer = true;

            Control target;
            if(needContainer)
                target = new Panel();
            else
                target = new PlaceHolder();    
            
            var propertyData = PropertyData as PropertyXhtmlString;
            if (propertyData != null) {
                foreach (var fragment in propertyData.StringFragments) {
                    bool isStaticFragment = fragment.GetType().Name == "StaticFragment" ? true : false;

                    //Remove closing tag in the beginning of content and opening tag in the end.
                    //The only way this this could happend is when we have dynamic content between two static content
                    //and then we want to render our own markup
                    if (isStaticFragment) {
                        
                        string content = fragment.InternalFormat;
                        content = AddClassToList(content);
                        if (content.StartsWith("</p>"))
                            content = content.Substring(4);
                        if (content.EndsWith("<p>"))
                            content = content.Substring(0, content.Length - 3);

                        var literal = new Literal {Text = content};
                        target.Controls.Add(literal);

                    } else {
                        target.Controls.Add(fragment.GetControl((PageBase) Page));
                    }
                }
                
                if(target is Panel)
                    CopyWebAttributes((Panel)target);

                Controls.Add(target);
            } else {
                base.CreateDefaultControls();
            }
        }
        #endregion
        #region private string AddClassToList(string markup)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="markup"></param>
        /// <returns></returns>
        private string AddClassToList(string markup) {
            string resultString = null;
            try {
                var regexObj =
                    new Regex("(<[uo]l(?![^>]*class=)[^>]*>)|<[uo]l[^>]+class=[\"']([^\"']*)[\"'][^>]*>",
                              RegexOptions.IgnoreCase | RegexOptions.Multiline);
                resultString = regexObj.Replace(markup, new MatchEvaluator(ComputeReplacement));
            } catch (ArgumentException) {
                // Syntax error in the regular expression
            }
            return resultString;

        }
        #endregion
        #region private string ComputeReplacement(Match m)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        private string ComputeReplacement(Match m) {
            const string className = "editorial-list";

            var replaceReg = new Regex("class\\s*=\\s*[\"']([^\"']*)[\"']");

            if (m.Groups[1].Value.Length == 0) {
                if (!(" " + m.Groups[2].Value + " ").Contains(className)) {
                    return replaceReg.Replace(m.Groups[0].Value, "class=\"$1 " + className + "\"");
                }
                return m.Groups[0].Value;
            }
            var value = m.Groups[0].Value.Trim();
            return value.Remove(value.Length - 1) + " class=\"" + className + "\">";

        }
        #endregion
    }
}